package com.gray.blog.interceptor;

import com.gray.blog.common.arg.BaseArg;
import com.gray.blog.common.util.IpAddressUtil;
import com.gray.blog.interceptor.pointcut.ControllerPointCut;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@Slf4j
@Aspect
@Order(0)
@Component
public class InitialInterceptor extends ControllerPointCut {

    @Around("controllerMethod()")
    public Object beforeInitial(ProceedingJoinPoint joinPoint) throws Throwable{
        Object result = null;
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        Object[] arguments = joinPoint.getArgs();
        if (arguments.length > 0) {
            // 设置请求ip
            if (arguments[0] instanceof BaseArg) {
                BaseArg baseArg = (BaseArg) arguments[0];
                String ip = IpAddressUtil.getIpAddress(request);
                baseArg.setLoginIp(ip);
            }
        }
        result = joinPoint.proceed();
        return result;
    }
}
